#!/bin/bash

# TMS 系统测试脚本

echo "=== TMS 系统功能测试 ==="

# 检查服务是否支持 reflection
echo "1. 检查 gRPC 服务反射支持..."
grpcurl -plaintext localhost:50051 list 2>/dev/null
if [ $? -eq 0 ]; then
    echo "✅ gRPC 反射支持正常"
else
    echo "❌ gRPC 服务未启动或不支持反射"
    echo "请先启动服务: cargo run --bin server"
    exit 1
fi

echo ""
echo "2. 测试车辆管理..."

# 创建车辆（使用随机车牌号避免冲突）
echo "创建车辆..."
RANDOM_PLATE="测试$(date +%s)"
VEHICLE_RESPONSE=$(grpcurl -plaintext -d "{
  \"license_plate\": \"$RANDOM_PLATE\",
  \"model\": \"解放J6\",
  \"max_weight\": 10.5,
  \"max_volume\": 45.0,
  \"type\": 0
}" localhost:50051 tms.TransportationService/CreateVehicle 2>/dev/null)

if [ $? -eq 0 ]; then
    echo "✅ 车辆创建成功"
    VEHICLE_ID=$(echo $VEHICLE_RESPONSE | jq -r '.id' 2>/dev/null)
    echo "车辆ID: $VEHICLE_ID"
else
    echo "❌ 车辆创建失败"
fi

echo ""
echo "3. 测试订单管理..."

# 创建订单
echo "创建订单..."
ORDER_RESPONSE=$(grpcurl -plaintext -d '{
  "customer_id": "customer-001",
  "pickup_address": "北京市朝阳区",
  "delivery_address": "上海市浦东新区",
  "weight": 500.0,
  "volume": 2.5
}' localhost:50051 tms.TransportationService/CreateOrder 2>/dev/null)

if [ $? -eq 0 ]; then
    echo "✅ 订单创建成功"
    ORDER_ID=$(echo $ORDER_RESPONSE | jq -r '.id' 2>/dev/null)
    echo "订单ID: $ORDER_ID"
else
    echo "❌ 订单创建失败"
fi

echo ""
echo "4. 测试运输计划..."

# 创建运输计划
echo "创建运输计划..."
PLAN_RESPONSE=$(grpcurl -plaintext -d '{
  "name": "测试运输计划",
  "description": "这是一个测试计划"
}' localhost:50051 tms.TransportationService/CreateTransportPlan 2>/dev/null)

if [ $? -eq 0 ]; then
    echo "✅ 运输计划创建成功"
    PLAN_ID=$(echo $PLAN_RESPONSE | jq -r '.id' 2>/dev/null)
    echo "计划ID: $PLAN_ID"
else
    echo "❌ 运输计划创建失败"
fi

echo ""
echo "5. 测试位置跟踪..."

if [ ! -z "$VEHICLE_ID" ]; then
    # 更新车辆位置
    echo "更新车辆位置..."
    LOCATION_RESPONSE=$(grpcurl -plaintext -d "{
      \"vehicle_id\": \"$VEHICLE_ID\",
      \"latitude\": 39.9042,
      \"longitude\": 116.4074,
      \"speed\": 60.5,
      \"heading\": 45.0
    }" localhost:50051 tms.TransportationService/UpdateLocation 2>/dev/null)

    if [ $? -eq 0 ]; then
        echo "✅ 位置更新成功"
    else
        echo "❌ 位置更新失败"
    fi
else
    echo "⚠️  跳过位置测试（车辆ID不可用）"
fi

echo ""
echo "6. 测试命令行客户端..."

# 测试CLI客户端
echo "测试车辆列表..."
cargo run --bin client -- vehicle list --page 1 --page-size 5 >/dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "✅ CLI客户端工作正常"
else
    echo "❌ CLI客户端测试失败"
fi

echo ""
echo "=== 测试完成 ==="
echo ""
echo "如需查看详细输出，请手动运行以下命令："
echo "grpcurl -plaintext localhost:50051 list"
echo "cargo run --bin client -- --help"